package com.bootadmin.controller.system.ao.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bootadmin.controller.system.ao.OperationAO;
import com.bootadmin.controller.system.dto.request.OperationPageListDTO;
import com.bootadmin.controller.system.dto.request.OperationSaveRequestDTO;
import com.bootadmin.core.utils.StringUtils;
import com.bootadmin.core.web.ResultJson;
import com.bootadmin.entity.Operation;
import com.bootadmin.enums.StateEnum;
import com.bootadmin.service.OperationService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author kongzm
 * @description: OperationAOImpl
 * @date 2022/3/10 15:43
 */
@Component
public class OperationAOImpl implements OperationAO {
    @Autowired
    private OperationService operationService;

    @Override
    public ResultJson save(HttpServletRequest request, OperationSaveRequestDTO operationSaveRequestDTO) {
        Operation operation = new Operation();
        if (operationSaveRequestDTO.getId() != null) {
            Operation op = operationService.getById(operationSaveRequestDTO.getId());
            operation.setVersion(op.getVersion());
        }
        BeanUtils.copyProperties(operationSaveRequestDTO, operation);
        operationService.saveOrUpdate(operation);
        return ResultJson.success();
    }

    @Override
    public ResultJson deleteById(HttpServletRequest request, Long id) {
        Operation operation = operationService.getById(id);
        int state = operation.getState().equals(StateEnum.ONE.getValue()) ? StateEnum.ZERO.getValue() : StateEnum.ONE.getValue();
        operation.setState(state);
        operationService.updateById(operation);
        return ResultJson.success();
    }

    @Override
    public ResultJson selectPageList(OperationPageListDTO operationPageListDTO) {
        QueryWrapper<Operation> wrapper = new QueryWrapper<>();
        if (!StringUtils.isTrimEmpty(operationPageListDTO.getName())) {
            wrapper.like("name", operationPageListDTO.getName().trim());
        }
        if (!StringUtils.isTrimEmpty(operationPageListDTO.getUrl())) {
            wrapper.like("url", operationPageListDTO.getUrl().trim());
        }
        if (!StringUtils.isTrimEmpty(operationPageListDTO.getModuleCode())) {
            wrapper.eq("module_code", operationPageListDTO.getModuleCode().trim());
        }
        wrapper.orderByDesc("id");

        Page<Operation> page = new Page<>(operationPageListDTO.getPageNum(), operationPageListDTO.getPageSize());
        IPage<Operation> list = operationService.page(page, wrapper);
        return ResultJson.success(list);
    }
}
